package com.atguigu.gulimall.order.rabbitListener;

import com.atguigu.common.constant.GulimallConstant;
import com.atguigu.common.constant.OrderConstant;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author liuq
 * @version 1.0
 * @description:
 * @date 2021/2/18 15:10
 */
@Component
@Slf4j
@RabbitListener(queues = OrderConstant.ORDER_RELEASE_ORDER_QUEUE_NAME)
public class OrderCloseListener {
    private final String className = this.getClass().getName();

    @Autowired
    private OrderService orderService;

    /**
     * 订单关闭
     *
     * @param orderEntity
     * @param message
     * @param channel
     */
    @RabbitHandler
    public void handleOrderClose(OrderEntity orderEntity, Message message, Channel channel) throws IOException {
        log.info("OrderCloseListener hand Order Close, {}", orderEntity);
        // 获取不到 CorrelationId
        log.info("message.getMessageProperties().getCorrelationId(), {}", message.getMessageProperties().getCorrelationId());
        // 可以获取 CorrelationId
        log.info("{} CorrelationId, {}", className, message.getMessageProperties().getHeaders().get(GulimallConstant.SPRING_RETURNED_MESSAGE_CORRELATION));
        try {
            orderService.closeOrder(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
